
<template>
  <view class="discover-container">
     <CustomHeader ref="customHeader"></CustomHeader>
    <!-- 顶部搜索区域 -->
    <view class="search-section">
      <view class="search-bar" @click="toggleSearch">
        <view class="search-icon-wrapper">
          <image
            src="/static/images/candidate/search.png"
            class="search-icon"
          ></image>
        </view>
        <view class="search-placeholder" v-if="!showSearchInput">
          <text class="placeholder-text">查询您感兴趣的文章</text>
        </view>
        <input
          v-else
          type="text"
          v-model="searchKeyword"
          placeholder="查询您感兴趣的文章"
          placeholder-class="placeholder"
          class="search-input"
          @input="onSearchInput"
          @confirm="doSearch"
          @blur="hideSearchInput"
          :focus="showSearchInput"
        />
      </view>
    </view>

    <!-- 文章列表 -->
    <view class="content-section">
      <!-- 空状态 -->
      <view v-if="articleList.length === 0 && !loading" class="empty-state">
        <image
          src="/static/images/candidate/empty.png"
          class="empty-image"
        ></image>
        <text class="empty-text">暂时没有相关文章~</text>
      </view>

      <!-- 文章列表 -->
      <scroll-view
        v-else
        class="article-list"
        scroll-y
        @scrolltolower="onScrollToLower"
        lower-threshold="50"
        :style="{ height: scrollHeight + 'px' }"
      >
        <view class="article-list-content">
          <!-- 加载中提示 -->
          <view v-if="loading && articleList.length === 0" class="loading-state">
            <text class="loading-text">加载中...</text>
          </view>

          <!-- 文章列表项 -->
          <view
            v-for="article in articleList"
            :key="article.id"
            class="article-item"
            @click="goToArticleDetail(article.id)"
          >
            <!-- 文章封面 -->
            <view class="article-cover-wrapper">
              <image
                :src="article.articleCover"
                class="article-cover"
                mode="aspectFill"
              ></image>
            </view>

            <!-- 文章内容 -->
            <view class="article-content">
              <text class="article-title">{{ article.title }}</text>
              <text class="article-summary">{{ getArticleSummary(article.content) }}</text>
              
              <!-- 文章底部信息 -->
              <view class="article-footer">
                <view class="publisher-info">
                  <image
                    :src="article.publisherFace || '/static/images/avatar.png'"
                    class="publisher-avatar"
                  ></image>
                  <text class="publisher-name">{{ article.publisher }}</text>
                </view>
                <view class="article-meta">
                  <text class="read-count">{{ formatReadCount(article.readCount) }}</text>
                  <text class="publish-time">{{ formatPublishTime(article.publishTime) }}</text>
                </view>
              </view>
            </view>
          </view>

          <!-- 加载更多 -->
          <view v-if="loadingMore" class="load-more">
            <text class="load-more-text">加载中...</text>
          </view>

          <!-- 没有更多数据 -->
          <view v-else-if="!hasMore && articleList.length > 0" class="no-more">
            <text class="no-more-text">没有更多数据了</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 底部tabbar -->
    <CustomTabBar :currentIndex="2" />
  </view>
</template>

<script setup>
import CustomHeader from "@/components/CustomHeader.vue";
import { ref, onMounted, nextTick } from "vue";
import CustomTabBar from "@/components/CustomTabBar.vue";
import { searchArticlesApi } from "@/api/article.js";

// 响应式数据
const searchKeyword = ref("");
const showSearchInput = ref(false);
const scrollHeight = ref(500);
const articleList = ref([]); // 文章列表

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const loading = ref(false);
const loadingMore = ref(false);

// 页面加载
onMounted(() => {
  nextTick(() => {
    calculateScrollHeight();
    // 初始化加载文章列表
    loadArticleList(true);
  });
});

// 计算滚动区域高度
const calculateScrollHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync();
    console.log("系统信息:", systemInfo);

    // 计算可用高度：总高度 - 顶部搜索区域 - tabbar高度 - 安全区域
    const topSectionHeight = uni.upx2px(120); // 搜索栏高度
    const tabbarHeight = uni.upx2px(98); // tabbar高度

    // 添加安全区域底部高度
    const safeAreaBottom = systemInfo.safeAreaInsets?.bottom || 0;

    let availableHeight =
      systemInfo.windowHeight -
      topSectionHeight -
      tabbarHeight -
      safeAreaBottom;

    // 确保最小高度
    availableHeight = Math.max(availableHeight, 300);

    scrollHeight.value = availableHeight;
    console.log(
      "计算的scroll-view高度:",
      scrollHeight.value,
      "原始窗口高度:",
      systemInfo.windowHeight
    );
  } catch (error) {
    console.error("计算滚动高度失败:", error);
    // 设置一个默认高度
    scrollHeight.value = 500;
  }
};

// 切换搜索输入框显示状态
const toggleSearch = () => {
  showSearchInput.value = true;
};

// 隐藏搜索输入框
const hideSearchInput = () => {
  if (!searchKeyword.value) {
    showSearchInput.value = false;
  }
};

// 搜索输入
const onSearchInput = (e) => {
  searchKeyword.value = e.detail.value;
};

// 执行搜索
const doSearch = () => {
  console.log("搜索关键词:", searchKeyword.value);
  // 重置分页参数并重新加载
  currentPage.value = 1;
  articleList.value = [];
  hasMore.value = true;
  loadArticleList(true);
};

// 加载文章列表
const loadArticleList = async (isRefresh = false) => {
  console.log(
    "获取文章列表 - isRefresh:",
    isRefresh,
    "currentPage:",
    currentPage.value
  );

  if (loading.value && !isRefresh) {
    console.log("正在加载中，跳过");
    return;
  }
  if (loadingMore.value && isRefresh) {
    console.log("正在加载更多，跳过刷新");
    return;
  }

  try {
    if (isRefresh) {
      currentPage.value = 1;
      loading.value = true;
      articleList.value = []; // 清空列表
      console.log("刷新模式 - 清空列表，重置页码");
    } else {
      if (!hasMore.value) {
        console.log("无更多数据可加载");
        return;
      }
      loadingMore.value = true;
      console.log("加载更多模式 - 页码:", currentPage.value);
    }

    // 构造请求参数
    const params = {
      pageNo: isRefresh ? 1 : currentPage.value,
      pageSize: pageSize.value,
    };

    // 只有当有搜索关键词时才添加到参数中
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value;
    }

    console.log("请求参数:", params);

    const res = await searchArticlesApi(params);
    console.log("文章列表响应:", res);

    if (res) {
      // 更新分页信息
      const totalPages = res.totalPages || 0;

      if (isRefresh) {
        articleList.value = res.list || [];
        currentPage.value = 1;
        console.log("刷新完成 - 当前列表长度:", articleList.value.length);
      } else {
        articleList.value.push(...(res.list || []));
        console.log("加载更多完成 - 当前列表长度:", articleList.value.length);
      }

      // 判断是否还有更多数据
      hasMore.value = currentPage.value < totalPages;
      console.log(
        "分页状态 - hasMore:",
        hasMore.value,
        "currentPage:",
        currentPage.value,
        "totalPages:",
        totalPages
      );
    }
  } catch (error) {
    console.error("获取文章列表失败:", error);
    uni.showToast({
      title: "获取文章列表失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
    loadingMore.value = false;
    console.log(
      "请求结束 - loading:",
      loading.value,
      "loadingMore:",
      loadingMore.value
    );
  }
};

// 滚动到底部加载更多
const onScrollToLower = () => {
  console.log(
    "滚动到底部 - 触发加载更多 - currentPage:",
    currentPage.value,
    "hasMore:",
    hasMore.value,
    "loadingMore:",
    loadingMore.value
  );

  if (loadingMore.value || !hasMore.value) {
    console.log("已在加载中或无更多数据");
    return;
  }

  const nextPage = currentPage.value + 1;
  currentPage.value = nextPage;
  loadArticleList(false);
};

// 获取文章摘要（截取前100个字符）
const getArticleSummary = (content) => {
  if (!content) return "";
  return content.length > 100 ? content.substring(0, 100) + "..." : content;
};

// 格式化阅读数量
const formatReadCount = (count) => {
  if (!count || count === 0) return "0阅读";
  
  if (count < 1000) {
    return `${count}阅读`;
  } else if (count < 10000) {
    return `${(count / 1000).toFixed(1)}k阅读`;
  } else if (count < 100000) {
    return `${(count / 10000).toFixed(1)}w阅读`;
  } else {
    return `${Math.floor(count / 10000)}w阅读`;
  }
};

// 格式化发布时间
const formatPublishTime = (time) => {
  if (!time) return "";
  
  try {
    const publishDate = new Date(time);
    const now = new Date();
    const diffTime = now - publishDate;
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) {
      return "今天";
    } else if (diffDays === 1) {
      return "昨天";
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      // 返回月-日格式
      const month = publishDate.getMonth() + 1;
      const day = publishDate.getDate();
      return `${month}-${day}`;
    }
  } catch (error) {
    console.error("时间格式化失败:", error);
    return time.split(" ")[0]; // 返回日期部分
  }
};

// 跳转到文章详情
const goToArticleDetail = (articleId) => {
  console.log("跳转到文章详情，articleId:", articleId);
  uni.navigateTo({
    url: `/pages/candidate/articleDetail?articleId=${articleId}`,
  });
};
</script>

<style lang="less" scoped>
.discover-container {
  background-color: #f8f8f8;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding-bottom: 98rpx; /* 给tabbar留空间 */
  overflow: hidden;
}

/* 搜索区域 */
.search-section {
  background-color: #ffffff;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.search-bar {
  height: 80rpx;
  background-color: #f8f8f8;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  position: relative;
}

.search-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15rpx;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
}

.search-placeholder {
  flex: 1;
  padding-left: 15rpx;
}

.placeholder-text {
  font-size: 28rpx;
  color: #b0b0b0;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  padding-left: 15rpx;
}

.placeholder {
  color: #b0b0b0;
}

/* 内容区域 */
.content-section {
  flex: 1;
  background-color: #f8f8f8;
  overflow: hidden;
  position: relative;
}

/* 文章列表 */
.article-list {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  /* 隐藏滚动条 */
  &::-webkit-scrollbar {
    display: none !important;
    width: 0 !important;
    height: 0 !important;
    background: transparent !important;
  }

  scrollbar-width: none !important; /* Firefox */
  -ms-overflow-style: none !important; /* IE 10+ */
}

.article-list-content {
  padding: 20rpx;
}

.article-item {
  background-color: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.article-cover-wrapper {
  width: 100%;
  height: 360rpx;
  overflow: hidden;
}

.article-cover {
  width: 100%;
  height: 100%;
}

.article-content {
  padding: 24rpx;
}

.article-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  line-height: 1.4;
  margin-bottom: 16rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.article-summary {
  font-size: 26rpx;
  color: #666666;
  line-height: 1.5;
  margin-bottom: 20rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  overflow: hidden;
  text-overflow: ellipsis;
}

.article-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.publisher-info {
  display: flex;
  align-items: center;
}

.publisher-avatar {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  margin-right: 12rpx;
}

.publisher-name {
  font-size: 24rpx;
  color: #999999;
}

.article-meta {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.read-count {
  font-size: 24rpx;
  color: #999999;
  position: relative;
}

.read-count::after {
  content: "·";
  margin-left: 16rpx;
  color: #cccccc;
}

.publish-time {
  font-size: 24rpx;
  color: #999999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 100rpx 0;
}

.empty-image {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 40rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

/* 加载状态 */
.loading-state,
.load-more,
.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
}

.loading-text,
.load-more-text,
.no-more-text {
  font-size: 28rpx;
  color: #999999;
}

/* 全局滚动条隐藏 */
::-webkit-scrollbar {
  display: none !important;
  width: 0 !important;
  height: 0 !important;
  background: transparent !important;
}

::-webkit-scrollbar-thumb {
  background: transparent !important;
}

::-webkit-scrollbar-track {
  background: transparent !important;
}
</style>